package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.client.service.ColumnServiceClient;
import com.hxkj.client.service.OptionColumnServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.enums.ColumnExceptionEnum;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.Column;
import com.hxkj.domain.po.OptionColumnTree;
import com.hxkj.domain.po.WebsiteAddr;
import com.hxkj.utils.TemplateModelUtils;
import com.platform.common.domain.exception.CustomException;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.*;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_COLUMN_TREE;


/**
 * @ClassName ColumnTreeMapDirective 多分类及其下级分类树封装文章标签解析
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/7/18 16:14
 * @Version 1.0
 */
@Component
@Log4j
public class ColumnTreeMapDirective extends AbstractDirective {
    @Autowired
    private OptionColumnServiceClient optionColumnServiceClient;

    @Autowired
    private ColumnServiceClient columnServiceClient;

    @Autowired
    private ArticleServiceClient articleServiceClient;

    /**
     * 输入参数，分类ID字符串
     */
    public static final String COLUMN_IDS = "columnIds";
    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";
    /**
     * 输入参数，是否排序,0：升序，1：降序
     */
    public static final String SORT = "sort";
    /**
     * 输入参数，获取起始条数
     */
    public static final String START = "start";
    /**
     * 输入参数，获取参数条数
     */
    public static final String COUNT = "count";
    /**
     * 输入参数，排序的字段，多个用","隔开
     */
    public static final String LOCATION_LEVEL = "locationLevel";

    /**
     * 输入参数，标题字数长度，多余的用"...."替代
     */
    public static final String TITLELEN = "titleLen";
    /**
     * 输入参数，是只查有图片的文章 0、为需要显示图片 1、为不需要显示图片
     */
    public static final String SHOW_IMG = "showImg";

    /**
     * 当前分类名称
     */
    public static final String COLUMN_NAME = "columnName";
    /**
     * 当前分类ID
     */
    public static final String COLUMN_ID = "columnId";
    /**
     * 当前分类地址
     */
    public static final String COLUMN_PATH = "columnPath";

    /**
     * 分类内容
     */
    public static final String COLUMN_TREE = "columnTree";
    /**
     * 下级分类
     */
    public static final String COLUMN_LIST = "columnList";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        env.getOut();
        try {
            //Mr.zheng:获取参数
            String ids = super.getString(COLUMN_IDS, params) == null ? (String) getCustomAttrbute(env, "columnId") : super.getString(COLUMN_IDS, params);
            Long siteId = super.getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : super.getLong(SITE_ID, params);
            //Mr.zheng:默认根据降序排序
            String sort = super.getString(SORT, params) == null ? "heat DESC" : super.getString(SORT, params);
            //Mr.zheng:默认取5条文章
            int start = super.getInt(START, params) == null ? 1 : super.getInt(START, params);
            //Mr.zheng:默认取5条文章
            int count = super.getInt(COUNT, params) == null ? 5 : super.getInt(COUNT, params);
            //Mr.zheng:默认取20字节
            int titleLen = super.getInt(TITLELEN, params) == null ? 20 : super.getInt(TITLELEN, params);
            //Mr.zheng:默认文章推荐等级不设置则为-1
            int locationLevel = super.getInt(LOCATION_LEVEL, params) == null ? -1 : super.getInt(LOCATION_LEVEL, params);
            //Mr.zheng:默认为1、不需要带图片
            int showImg = super.getInt(SHOW_IMG, params) == null ? 1 : super.getInt(SHOW_IMG, params);

            String note = super.getNote(env);
            if (ids.length() == 0) {
                log.info("分类ID字符串为空");
            }
            Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
            Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
            String urlContext = siteCtxMap.get(siteId);

            String columnIds[] = ids.split(",");
            List<Map<String, Object>> columnMapList = new ArrayList<>();
            for (int i = 0; i < columnIds.length; i++) {
                Map<String, Object> map = new HashMap<>();
                //Mr.zheng:封装查询参数
                Column column = new Column();
                column.setColumnId(Long.valueOf(columnIds[i]));
                column.setSiteId(siteId);
                //Mr.zheng:封装当前选中的分类信息
                column = columnServiceClient.getColumn(column);

                WebsiteAddr websiteAddr = getWebSiteAddr(siteId);
                if (StringUtils.isNotBlank(note)) {
                    if (column == null) column = new Column();
                    column.setManuscriptPath(websiteAddr.getIpAdd() + column.getManuscriptPath());
                }else {
                    // 静态文件分类及下级文章链接加前缀
                    if (StringUtils.isNotBlank(urlContext)) {
                        if (column == null) column = new Column();
                        column.setManuscriptPath(urlContext + column.getManuscriptPath());
                    }
                }
                map.put(COLUMN_NAME, column.getColumnName());//选中的分类名称
                map.put(COLUMN_PATH, column.getManuscriptPath());//选中的分类路径
                map.put(COLUMN_ID, column.getColumnId());//选中的分类ID

                column.setSort(sort);
                column.setCount(count);
                column.setTitleLen(titleLen);
                OptionColumnTree columnTree = optionColumnServiceClient.getColumnTree(column);

                if (StringUtils.isNotBlank(note)) {
                    columnTree.setManuscriptPath(websiteAddr.getIpAdd() + columnTree.getManuscriptPath());
                    for (OptionColumnTree octe : columnTree.getChildren()) {
                        octe.setManuscriptPath(websiteAddr.getIpAdd() + octe.getManuscriptPath());
                        for (Article article : octe.getArticleList()) {
                            article.setManuscriptPath(websiteAddr.getIpAdd() + article.getManuscriptPath());
                        }
                    }
                }else {
                    // 静态文件分类及下级文章链接加前缀
                    if(StringUtils.isNotBlank(urlContext)) {
                        columnTree.setManuscriptPath(urlContext + columnTree.getManuscriptPath());
                        columnTree.setManuscriptPath(urlContext + columnTree.getManuscriptPath());
                        for (OptionColumnTree octe : columnTree.getChildren()) {
                            octe.setManuscriptPath(urlContext + octe.getManuscriptPath());
                            for (Article article : octe.getArticleList()) {
                                article.setManuscriptPath(urlContext + article.getManuscriptPath());
                            }
                        }
                    }
                }
                Article article = new Article();
                if (locationLevel > 0) {
                    article.setLocationLevel(locationLevel);
                    article.setSiteId(siteId);
                    article.setSort(sort);
                    article.setStart(start - 1);
                    article.setCount(count);
                    article.setTitleLen(titleLen);
                    article.setShowImg(showImg);
                    List<Article> articleList = articleServiceClient.getArticleListByParam(article);
                    if (StringUtils.isNotBlank(note)) {
                        for (Article art : articleList) {
                            art.setManuscriptPath(websiteAddr.getIpAdd() + art.getManuscriptPath());
                        }
                    }else {
                        // 静态文件分类及下级文章链接加前缀
                        if(StringUtils.isNotBlank(urlContext)) {
                            for (Article item : articleList) {
                                item.setManuscriptPath(urlContext + item.getManuscriptPath());
                            }
                        }
                    }
                    columnTree.setArticlePush(articleList);
                }

                map.put(COLUMN_TREE, columnTree);//一级分类信息
                map.put(COLUMN_LIST, columnTree.getChildren());//二级分类及其有可能的三级分类，和文章列表集合
                columnMapList.add(map);
            }
            env.setVariable("columnMapList", DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(columnMapList));

            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    maps.put(CMS_COLUMN_TREE, "");
                    maps.put(SITE_ID, String.valueOf(super.getLong(SITE_ID, params)));
                    maps.put(COLUMN_IDS, super.getString(COLUMN_IDS, params));
                    maps.put(SORT, String.valueOf(super.getString(SORT, params)));
                    maps.put(START, String.valueOf(super.getInt(START, params)));
                    maps.put(COUNT, String.valueOf(super.getInt(COUNT, params)));
                    maps.put(TITLELEN, String.valueOf(super.getInt(TITLELEN, params)));
                    maps.put(LOCATION_LEVEL, String.valueOf(super.getInt(LOCATION_LEVEL, params)));
                    maps.put(SHOW_IMG, String.valueOf(super.getInt(SHOW_IMG, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                throw new RuntimeException("频道所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
